package scenic;

import java.awt.Rectangle;
import java.util.LinkedList;
import java.util.ListIterator;


class CacheImage {
	private Image cacheImage;
	private LinkedList glyphList = new LinkedList();
	private LinkedList oldGlyphList = new LinkedList();
	private int top;
	private int rowHeight;
	private int rowX;
	private int width;
	private int height;
	
	public CacheImage(Image image) {
		cacheImage = image;
		width = image.getWidth();
		height = image.getHeight();
	}
	
	public Image getCacheImage() {
		return cacheImage;
	}
	
	public Rectangle addImage(ImageInfo image) {
		int w = image.width;
		int h = image.height;
		
		if(cacheImage.getFormat() != image.format)
			return null;

		if(rowX + w > width)
		{
			top += rowHeight;
			rowHeight = 0;
			rowX = 0;
		}
		if(top + h > height)
		{
			if(h > height)
				return null;
			top = 0;
			rowX = 0;
			rowHeight = h;
			ListIterator itr = oldGlyphList.listIterator();
			
			while(itr.hasNext())
				((Rectangle)itr.next()).width = -1;
			oldGlyphList = glyphList;
			glyphList = new LinkedList();
		}
		if(h > rowHeight)
			rowHeight = h;
		
		ListIterator itr = oldGlyphList.listIterator();
		while(itr.hasNext())
		{
			Rectangle r = (Rectangle)itr.next();
			
			if(r.y >= top + rowHeight)
				break;
			r.width = -1;
			itr.remove();
		}
		
		Rectangle r = new Rectangle(rowX, top, w, h);
		
		rowX += w;		
		glyphList.addLast(r);
		cacheImage.write(r.x, r.y, r.width, r.height, image.data);
		
		return r;
	}
}
